package com.yl.auth.easyexcel.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.yl.auth.mapper.LaorenMapper;
import com.yl.auth.model.entity.Laoren;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;

/**
 * @author 王庆梁
 * @datetime 2023/7/11 22:42
 * @description 类对象
 */
@Slf4j
@NoArgsConstructor
public class ExcelLaoRenDTOListener extends AnalysisEventListener<Laoren> {
    private static  final Integer BATCH_COUNT = 5;
    List<Laoren> list = new ArrayList<>();

    private LaorenMapper laorenMapper;
    //传入mapper对象
    public ExcelLaoRenDTOListener(LaorenMapper laorenMapper) {
        this.laorenMapper = laorenMapper;
    }

    @Override
    public void invoke(Laoren data, AnalysisContext context) {
        log.info("解析到一条记录：{}",data);
        list.add(data);
        if(list.size()>=BATCH_COUNT){
            saveData();
            list.clear();
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        // 这里也要保存数据，确保最后遗留的数据也存储到数据库
        saveData();
        log.info("所有数据解析完成！");
    }

    private void saveData() {
        log.info("{}条数据，开始存储数据库!",list.size());
        log.info("存储数据库成功!");
    }
}
